import React, { FC, useEffect, useRef, useState } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { Image, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { useBoolean, useReactive } from 'ahooks';
import Tools from '../../../utils/Tools.ts';
import { Dialog, ListItem } from '@rneui/base';
import { SafeAreaView } from 'react-native-safe-area-context';
import { launchImageLibrary } from 'react-native-image-picker';
import ImageCropPicker from 'react-native-image-crop-picker';
import UserRequest from '../../../request/userRequest.ts';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import { updateUserInfo } from '../../../redux/reducers/app.ts';
import { Box, Button, FormControl, Input, Modal, useToast } from 'native-base';
import Spinner from 'react-native-loading-spinner-overlay';

interface IAccountInformationScreenProps {
  navigation: NavigationProp<any, 'accountInformationScreen'>;
  route: RouteProp<{ accountInformationScreen: any }, 'accountInformationScreen'>;
}
const AccountInformationScreen: FC<IAccountInformationScreenProps> = ({ navigation }) => {
  const userInfo = useSelector((state: RootState) => state.userInfo);
  const [spinner, setSpinner] = useState<{ state: boolean; text: string }>({ state: false, text: '' });
  const dispatch = useDispatch<AppDispatch>();
  const [visible, { toggle, setFalse }] = useBoolean(false);
  const [enterName, setEnterName] = useState<string>('');
  const editNameInputRef = useRef<TextInput | null>(null);
  const toast = useToast();
  const [modalVisible, setModalVisible] = React.useState(false);
  const modifyPhonemodifyPhone = useReactive({ phone: userInfo.phone, code: '' });
  const [waitingTime, setWaitingTime] = useState(0);

  useEffect(() => {
    let timer: NodeJS.Timeout | null = null;
    if (waitingTime > 0) {
      timer = setInterval(() => {
        setWaitingTime((prevTime) => prevTime - 1);
      }, 1000);
    }
    return () => {
      if (timer) clearInterval(timer);
    };
  }, [waitingTime]);

  /**
   * 打开修改名称
   */
  const handleOpenEditNameDialog = () => {
    setEnterName('');
    toggle();
    setTimeout(() => {
      editNameInputRef.current?.focus();
    }, 300);
  };

  /**
   * 选择头像修改头像
   */
  const handleOpenSelectAvatar = () => {
    launchImageLibrary({ selectionLimit: 1, mediaType: 'photo' }).then((res) => {
      if (res.didCancel) return;
      const uri: string = res.assets![0].uri!;
      ImageCropPicker.openCropper({
        path: uri,
        mediaType: 'photo',
        width: 200,
        height: 200,
      })
        .then(async (image) => {
          const { nickName } = userInfo!;
          const imageBase64 = await Tools.convertFileToBase64(image.path);
          if (!imageBase64) return;
          fetchUpdateUser(nickName, imageBase64, '修改头像中...');
        })
        .catch(() => {});
    });
  };

  /**
   * 确认修改名称
   */
  const handleOpenUpdateNickName = () => {
    if (!enterName) {
      toast.show({ description: '请输入新的名称' });
      return;
    }
    setFalse();
    fetchUpdateUser(enterName, userInfo!.imageUrl, '修改名称...');
  };

  /**
   * 更新用户信息
   * @param nickName
   * @param image
   * @param text
   */
  const fetchUpdateUser = (nickName: string, image: string, text: string) => {
    setSpinner({ state: true, text });
    UserRequest.UpdateUser({ image, nickName })
      .then(async (res) => {
        toast.show({ description: '修改成功' });
        setSpinner((prevState) => {
          return { ...prevState, state: !prevState.state };
        });
        dispatch(updateUserInfo({ ...userInfo, nickName, imageUrl: res.data || image }));
      })
      .catch(() => {
        setSpinner((prevState) => {
          return { ...prevState, state: !prevState.state };
        });
      });
  };

  /**
   * 获得验证码
   */
  const handleObtainVerificationCode = () => {
    const { phone } = modifyPhonemodifyPhone;
    if (!phone) {
      toast.show({ description: '请输入手机号' });
    }
    UserRequest.FetchSMS({ mobile: phone, smsType: 103 }).then(() => {
      toast.show({ description: '发送验证码成功，请注意查看短信' });
      setWaitingTime(60);
    });
  };

  /**
   * 更换手机号
   */
  const handleChangePhoneNumber = () => {
    const { phone, code } = modifyPhonemodifyPhone;
    UserRequest.UpdateUserPhone({ phone, code }).then(() => {
      setModalVisible(false);
      modifyPhonemodifyPhone.code = '';
      setWaitingTime(0);
      dispatch(updateUserInfo({ ...userInfo, phone }));
      toast.show({ description: '修改手机号成功' });
    });
  };

  return (
    <>
      <Spinner visible={spinner.state} textContent={spinner.text} color={CommonStyle.mainColor} overlayColor={'rgba(0, 0, 0, 0.1)'} textStyle={CommonStyle.spinnerText} />
      <SafeAreaView style={styles.root}>
        <Image style={styles.avatarImg} source={{ uri: userInfo.imageUrl }} />
        <View style={styles.textBox}>
          <Text style={styles.text}>{userInfo.nickName}</Text>
        </View>
        <View style={[styles.textBox, { marginBottom: 20 }]}>
          <Text style={styles.text}>{Tools.ProtectingPhoneNumbers(userInfo.phone)}</Text>
        </View>

        <TouchableOpacity style={{ width: '100%' }} onPress={handleOpenEditNameDialog}>
          <ListItem style={styles.list} bottomDivider>
            <ListItem.Content>
              <ListItem.Title style={styles.listText}>修改名称</ListItem.Title>
            </ListItem.Content>
            <ListItem.Chevron />
          </ListItem>
        </TouchableOpacity>
        <TouchableOpacity style={{ width: '100%' }} onPress={handleOpenSelectAvatar}>
          <ListItem style={styles.list} bottomDivider>
            <ListItem.Content>
              <ListItem.Title style={styles.listText}>修改头像</ListItem.Title>
            </ListItem.Content>
            <ListItem.Chevron />
          </ListItem>
        </TouchableOpacity>
        <TouchableOpacity
          style={{ width: '100%' }}
          onPress={() => {
            modifyPhonemodifyPhone.phone = userInfo.phone;
            setModalVisible(!modalVisible);
          }}
        >
          <ListItem style={styles.list} bottomDivider>
            <ListItem.Content>
              <ListItem.Title style={styles.listText}>更换手机号</ListItem.Title>
            </ListItem.Content>
            <ListItem.Chevron />
          </ListItem>
        </TouchableOpacity>
      </SafeAreaView>

      <Dialog overlayStyle={styles.dialog} isVisible={visible} onBackdropPress={() => toggle()}>
        <Dialog.Title title="修改名称" />
        <TextInput ref={editNameInputRef} placeholder={userInfo.nickName} value={enterName} onChangeText={(name) => setEnterName(name)} />
        <Dialog.Actions>
          <Dialog.Button title="取消" onPress={() => toggle()} />
          <Dialog.Button title="确定" onPress={handleOpenUpdateNickName} />
        </Dialog.Actions>
      </Dialog>

      <Modal closeOnOverlayClick={false} avoidKeyboard={true} isOpen={modalVisible} onClose={() => setModalVisible(false)} size={'xl'}>
        <Modal.Content>
          <Modal.CloseButton />
          <Modal.Header>更换手机号</Modal.Header>
          <Modal.Body>
            <FormControl>
              <FormControl.Label>手机号</FormControl.Label>
              <Box alignItems="center">
                <Input keyboardType={'numeric'} mx="3" placeholder="请输入手机号" w="100%" h="10" value={modifyPhonemodifyPhone.phone} onChangeText={(text: string) => (modifyPhonemodifyPhone.phone = text)} />
              </Box>
            </FormControl>
            <FormControl mt="2">
              <FormControl.Label>验证码</FormControl.Label>
              <Box alignItems="center">
                <Input
                  keyboardType={'numeric'}
                  placeholder="请输入验证码"
                  w="100%"
                  h="10"
                  onChangeText={(text: string) => (modifyPhonemodifyPhone.code = text)}
                  InputRightElement={
                    <Button size="xs" rounded="none" h="full" isDisabled={waitingTime > 0} backgroundColor={CommonStyle.mainColor} onPress={handleObtainVerificationCode}>
                      {waitingTime > 0 ? waitingTime : '获取验证码'}
                    </Button>
                  }
                />
              </Box>
            </FormControl>
            <Text style={[CommonStyle.tipsText, { marginTop: 10 }]}>注:您已绑定此手机号，输入新手机号可更换绑定</Text>
          </Modal.Body>
          <Modal.Footer>
            <Button isDisabled={!(modifyPhonemodifyPhone.phone && modifyPhonemodifyPhone.code)} size={'md'} width={'100%'} backgroundColor={CommonStyle.mainColor} onPress={handleChangePhoneNumber}>
              确认更换
            </Button>
          </Modal.Footer>
        </Modal.Content>
      </Modal>
    </>
  );
};

const styles = StyleSheet.create({
  root: { flex: 1, backgroundColor: '#fff', flexDirection: 'row', justifyContent: 'center', flexWrap: 'wrap' },
  avatarImg: { width: 110, height: 110, marginBottom: 20, borderRadius: 8 },
  textBox: { width: '100%', textAlign: 'center' },
  text: { textAlign: 'center', fontWeight: 'bold', fontSize: 16, color: CommonStyle.textColor },
  list: { width: '100%', marginTop: 5 },
  listText: { fontSize: 14, color: CommonStyle.textColor, fontWeight: 'bold' },
  dialog: { width: '90%', backgroundColor: '#fff' },
});
export default AccountInformationScreen;
